<template>
    <div class="detail-page">
        <div class="header">
            <mooc-progress-header v-if="isBuy && isApp" :data="covertData(detail, 'header')"/>
            <mooc-detail-header v-else :data="covertData(detail, 'header')"/>
        </div>
        <div class="main-content" :class="{block: !isBuy || lastCatalogue || !isApp}">
            <van-tabs v-model:active="active" scrollspy sticky ref="vanTabRef">
                <van-tab title="简介" v-if="!isBuy || !isApp">
                    <div class="module">
                        <introduct :data="covertData(detail, 'intro')"/>
                    </div>
                </van-tab>
                <van-tab title="目录">
                    <div class="module">
                        <Catalogue
                            :list="catalogueList"
                            :data="covertData(detail, 'catalogue')"
                            @to-detail="catalogueDetail"
                        />
                    </div>
                </van-tab>
                <van-tab title="作业">
                    <div class="module">
                        <home-work @view-homework="viewHomework" :is-buy="isBuy"/>
                    </div>
                </van-tab>
                <van-tab :title="`评价  ${page.total}`" v-if="!isBuy || !isApp">
                    <div class="module">
                        <Comment
                            :list="comments"
                            :data="covertData(detail, 'comment')"
                            :page="page.pageIndex"
                            :total="page.total"
                            :finished="finished"
                            :loading="commentLoading"
                            @load-data="loadMore"
                        />
                    </div>
                </van-tab>
            </van-tabs>
        </div>
        <div class="study-btn" v-if="!isBuy">
            <p class="btn" @click="applyBtn">报名学习</p>
        </div>
        <!-- 在APP应用里 -->
        <div class="study-btn studying" v-if="isBuy && lastCatalogue && isApp">
            <div class="study-info">
                <img src="@/assets/images/time-icon.png" alt="" class="icon">
                <span class="title">上次学到：{{lastCatalogue.catalogueName}}</span>
            </div>
            <p class="btn" @click="toStudy()">继续学习</p>
        </div>
        <!-- 不在APP应用里 -->
        <div class="study-btn studying" v-if="isBuy && !isApp">
            <p class="btn btn-wx" @click="goApp">已加入，前往APP学习</p>
        </div>
    </div>
    <van-popup v-model:show="show" position="bottom" round :close-on-click-overlay="false">
        <div class="apply-content">
            <p class="title">报名成功</p>
            <div class="bg">
                <empty :image="require('@/assets/images/success-apply.png')" addTip="恭喜你，已报名成功，开始学习吧" :size="[260, 160]"/>
            </div>
            <p class="btn" @click="closePop">好的</p>
        </div>
    </van-popup>
</template>

<script setup>
import moocDetailHeader from './components/mooc-detail-header.vue'
import moocProgressHeader from './components/mooc-progress-header.vue'
import MoreInfo from './components/more-info.vue'
import Catalogue from './pane/catalogue';
import HomeWork from './components/homework-list.vue'
import Comment from './pane/comment.vue'
import introduct from './components/introduction.vue'
import Empty from '@/components/empty.vue'
import {computed, onMounted, ref, watch, reactive, nextTick, onUnmounted} from 'vue';
import envJudge from '@/lib/judge-env';
import {useStore} from 'vuex'
import {useRoute, useRouter} from 'vue-router';
import { handleErrorPage } from '@/lib/tools.js';

const route = useRoute();
const router = useRouter();
const store = useStore();
const env = envJudge();
const isApp = reactive(['IOS', 'android'].includes(env));
const active = ref(0)
const vanTabRef = ref(null) // tab标签实例
// 慕课详情数据
const detail = ref({});
// popups
const show = ref(false)
const catalogueList = ref([]) // 目录
const comments = ref([]); // 评论列表
const page = reactive({ // 评论参数
    pageIndex: 1,
    pageSize: 10,
    total: 0
});
const lastCatalogue = ref('') // 最后学习数据
const finished = ref(true); // 评论是否有更多
const commentLoading = ref(false);
const showTab = ref(false) // 显示tab时设置app标题
const isBuy = computed(() => detail.value.isBuy) // 是否报名
const isCreator = computed(() => detail.value.isMyCreate) // 是否是创建人

// 品牌信息
const brandInfo = computed(() => {
    return store.state.brand?.publishBrand;
})

// 用户信息
const currentUser = computed(() => {
    return store.state?.currentUser || {};
});

// 用户信息 和 详情
const shareInfo = computed(() => {
    return {currentUser: currentUser.value, detail: detail.value};
});


watch(() => showTab.value, (val) => {
    if(isApp) setAppTitle()
})

watch(() => shareInfo.value, (val) => {
    if(isApp && val.currentUser?.userId && val.detail?.id) {
        shareFunc();
    }
}, {deep: true});

// 获取慕课详情
async function getMoocDetail () {
    try {
        let res = await  G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })
        detail.value = res.data || {};

        getComments();
        queryCatalogueTree()
        detail.value.isBuy && getLastStudy()
        // 不是购买者 并且不是创建人
        let notCourseUser = !detail.value?.isBuy && !detail.value?.isMyCreate;
        
        let isPublish = detail.value?.publishState == 1 && detail.value?.state == 4;

        // 课程未发布 只有创建人能看 已报名的人也能看
        if (!isPublish && notCourseUser) {
            handleErrorPage('unpublished', route.params.moocId);
        }
    } catch(_err) {
        console.log(_err, '===============detail_err=============');
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            handleErrorPage('delete', route.params.moocId);
        } else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

// 转换详情数据分发各个组件需要的值
function covertData(data = {}, type){
    let keyMap = {
        header: ['assessAppraiseId', 'title', 'cover', 'classifyList', 'courseWareCount', 'myScore', 'buyUserCount', 'completeHomeworkCount', 'completeCourseWareCount', 'homeworkCount', 'classHour', 'score'],
        intro: ['description', 'courseList'],
        comment: ['assessAppraiseId', 'courseList'],
        catalogue: ['courseList', 'isBuy']
    }
    let formatObj = {}
    keyMap[type].forEach(item => {
        formatObj[item] = data[item]
    })
    return formatObj
}

// 获取目录
function queryCatalogueTree() {
    if(!detail.value.courseList){
        return
    }
    G_transmit('moocCatalogue', {
            name: 'moocCatalogue',
            data: {
                courseId: detail.value.courseList[0].id,
                moocId: route.params.moocId
            }
        })
        .then((res) => {
            catalogueList.value = handleData(res.data);
        })
        .catch((err) => {
            console.log(err);
        })
        .finally(() => {
        })
}

// 处理目录数据
function handleData(data) {
    if ( !data.length ) return []
    return data.map(item => {
        return {
            ...item,
            toggle: item.maxDeep > 0,
            isToggle: item.maxDeep > 0
        }
    })
}

function loadMore(pageIndex){
    // console.log(page, 'page')
    page.pageIndex = pageIndex
    getComments()
}

// 获取评论列表
function getComments() {
    commentLoading.value = true;
    G_transmit('courseCommentList', {
        data: {
            moocId: route.params.moocId,
            pageIndex: page.pageIndex,
            pageSize: page.pageSize,
            assessAppraiseId: detail.value.assessAppraiseId
        }
    }).then(({ data }) => {
        if (page.pageIndex <= 1) {
            comments.value = data.rows || [];
        } else {
            comments.value = comments.value.concat(data.rows || []);
        }
        page.total = data.total;

        finished.value = ((data.rows && data.rows?.length || 0) < page.pageSize);
        commentLoading.value = false;
    });
}

// 报名学习
function applyBtn() {
    G_transmit('obtainMooc', {
        data: {
            buyType: 1, // 选课方式 1-自己选课（购买）
            moocId: route.params.moocId,
            price: 0
        }
    }).then((res) => {
        show.value = true
    }).catch(_err => {
        console.log(_err);
    })
}

// 最近学习记录
function getLastStudy () {
    G_transmit('getLastStudyCatalogue', {
        queries: {
            moocId: route.params.moocId // 慕课Id
        }
    }).then(async (res) => {
        lastCatalogue.value = res?.data?.lastStudy || ''
    })
}

// 跳转学习
function toStudy(catalogueId = ''){
    let cateId = catalogueId || lastCatalogue.value.catalogueId
    let params = {
        moocId: detail.value.id
    }
    let query = {
        catalogueId: cateId, 
        courseId: detail.value.courseList[0].id
    }
    jumpPage('catalogueDetail', params, query, false)
}

// 跳转目录详情
function catalogueDetail(data){
    if(!isBuy.value && !isCreator.value){
       return G_dispatchEvent('toast', { message: '请先报名学习再查看', type: 'info'});
    }
    if(!isApp){
       return G_dispatchEvent('toast', { message: '请前往APP学习', type: 'info'});
    }
    toStudy(data.catalogueId)
}

// 查看作业
function viewHomework(item){
    if(!isBuy.value){
        return G_dispatchEvent('toast', { message: '请先报名学习再查看', type: 'info'});
    }
    if(!isApp){
       return G_dispatchEvent('toast', { message: '请前往APP学习', type: 'info'});
    }
    const params = {
        moocId: route.params.moocId,
        homeworkId: item.homeWorkId
    }
    let name = item.isDone == 0 ? 'homework' : 'homeworkDetail'
    jumpPage(name, params, {}, true)
}
function jumpPage(url = '', params = {}, query = {}, pullRefresh){
    store.dispatch('jsBridge/disposeBridge', {
        method: 'goNewPage',
        url: {
            name: url,
            params,
            query
        },
        naviBarHidden: false,
        data: {
            pullRefresh // 看课页禁止下拉更新
        }
    })
}
function setAppTitle(){
    store.dispatch('jsBridge/disposeBridge', {
        method: 'setNativeTitle',
        options: {
            title: showTab.value ? detail.value.title : '',
            naviBarHidden: false,
            showBack: false
        }
    });
}
// 关闭报名成功弹窗刷新状态
function closePop(){
    show.value = false
    getMoocDetail()
}

function scrollFn() {
    let tab = document.querySelector('.main-content .van-sticky')
    let header = document.querySelector('.header')
    if (!tab) return
    let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
    showTab.value = scrollTop >= header.clientHeight
    if ( scrollTop <= header.clientHeight + 150) {
        tab.style.display = 'none'
    }else{
        tab.style.display = 'block'
        nextTick(() => {
            vanTabRef.value && vanTabRef.value.resize()
        })
    }
}

function goApp() {
    let url = window.location.href;
    if(route.name === 'shareDetail') {
        url.replace('/share', '/detail');
    }
    let appUrl = `/appidx/download?func=miniProgram&url=${encodeURIComponent(url)}`
    G_go(appUrl);
}

// 分享配置
function shareFunc() {
    let url = router.resolve({
        name: 'shareDetail',
        params: {
            moocId: route.params.moocId
        }
    }).href;
    store.dispatch('jsBridge/SXYJSBridge', {
        method: 'shareConfig',
        fun: 'shareConfig',
        data: {
            encriptLinkEnabled: true, // 加密开关
            encriptLinkParams: {
                element: 'detail',
                objType: 'mooc',
                type: 'outside', 
                objId: route.params.moocId,
            },
            dtBrandId: brandInfo.value.brand,
            popup: false,
            title: detail.value.title || '',
            url: `${location.origin}${url}`,
            content: `老师您好，${currentUser.value.name}老师给您分享了“${detail.value.title}”的慕课，您可以使用访问链接查看哦。`,
            linkContent: `老师您好，${currentUser.value.name}老师给您分享了“${detail.value.title}”的慕课，您可以使用访问链接查看哦。`,
            icon: detail.value.cover
        },
        callback: () => {
            // window.$tips.Toast('链接已复制到剪切板，去分享给好友吧');
        }
    });
}

onMounted(() => {
    getMoocDetail();
    window.addEventListener('scroll', scrollFn, true);
})
onUnmounted(() => {
    window.removeEventListener('scroll', scrollFn)
})
</script>

<style lang="scss" scoped>
.detail-page {
    font-family: PingFangSC-Regular, PingFang SC;
    background-color: #fff;
    width:100%;
    min-height: 100vh;
    height:100%;
    .module{
        border-top: 10px solid #F5F5F5;
    }
    :deep(.main-content){
        .van-tab {
            // font-size: 15px;
            // font-weight: 400;
            // color: #6E7074;
            // line-height: 24px;
        }
        .van-sticky{
            display: none;
        }
        .van-tab--active {
            font-size: 18px;
            font-weight: 600;
            color: #171A1D;
        }
        .van-tabs__line {
            width: 24px;
            height: 3px;
            background: linear-gradient(270deg, #00BDFE 0%, #0084F6 100%);
            border-radius: 2px;
            // bottom: 8px;
        }
    }
    .block{
        padding-bottom: 94px;
    }
    .study-btn{
        position: fixed;
        left:0;
        bottom: 0;
        width:100%;
        height: 94px;
        border-top: 10px solid #F5F5F5;
        background-color: #fff;
        padding-top: 8px;
        box-sizing: border-box;
        
        .btn{
            width:345px;
            height: 44px;
            background: #0084F6;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 400;
            color: #FFFFFF;
            text-align: center;
            margin: 0 auto;
            line-height: 44px;
        }
    }
    .studying{
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 15px;
        box-sizing: border-box;
        .study-info{
            display: inline-flex;
            align-items: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
            .icon{
                width:15px;
                height:15px;
                margin-right: 4px;
            }
            .title{
                font-size: 15px;
                font-weight: 400;
                color: #6E7074;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                // flex: 1;
            }
        }
        .btn{
            width:104px;
            background: #0084F6;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 400;
            color: #FFFFFF;
            margin-left: 15px;
        }
        .btn-wx {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
.apply-content{
    width:100%;
    height:390px;
    background-color: #fff;
    .title{
        width: 100%;
        height: 48px;
        border-bottom: 1px solid #eee;
        font-size: 16px;
        font-weight: 600;
        color: #171A1D;
        text-align: center;
        line-height: 48px;
    }
    .btn{
        width:345px;
        height:44px;
        background: #EFF0F2;
        border-radius: 4px;
        font-size: 16px;
        font-weight: 400;
        color: #171A1D;
        text-align: center;
        line-height: 44px;
        margin: 0 auto;
    }
}

</style>
